/* 
 * File:   ADCXpackDetector.cpp
 * Author: minaev
 * 
 * Created on 23 Декабрь 2013 г., 12:23
 */

#include "ADCXpackDetector.h"
#include "Xpack.h"

ADCXpackDetector::ADCXpackDetector(XbeeContainer* xcont) : XpackDetector(xcont) {
}

uint8_t ADCXpackDetector::getXpackType() {
    return XAPI_RX_IO_RECV;
}
//[ 0x92, 
//  0x0, 0x13, 0xa2, 0x0, 0x40, 0xa1, 0x9f, 0xb0, 
//  0x44, 0xae, 0x41, 0x1, 0x0, 0x6, 0x1, 0x0, 0x2, 0x3, 0xd7, ]  --- classic ADC
//  0x55, 0x17, 0x41, 0x1, 0x0, 0x6, 0x1, 0x0, 0x2, 0x3, 0xd7, ]  --- also ADC
//[ 0x92, 0x0, 0x13, 0xa2, 0x0, 0x40, 0xa1, 0x9f, 0xb0, 0x55, 0x17, 0x41, 0x1, 0x0, 0x6, 0x1, 0x0, 0x2, 0x3, 0xd6, ]

bool ADCXpackDetector::isXpackValid(Xpack* pack) {
    if (pack->getLength() > 16) {
        return *(uint32_t*) (pack->getData() + 11)
                == 0x06000141 &&
                *(uint8_t*) (pack->getData() + 15) == 0x01; //only with ADC
    } else {
        return false;
    }
}

void ADCXpackDetector::action(Xpack* pack) {
    uint8_t reqStat;
    uint8_t curStat;
    uint32_t buf;

    int nblock = xcont->findById(*(uint32_t*) (pack->getData() + 5));
    if (nblock != -1) {
        reqStat = *(uint8_t*) xcont->getParam(nblock, SLN_XREQSTAT);
        curStat = *(uint8_t*) xcont->getParam(nblock, SLN_XSTAT);

        xcont->setParam(nblock, SLN_XADC, (void*) (pack->getData() + 18));

        if (*(uint16_t*) xcont->getParam(nblock, SLN_XFIXADC) == 0) {
            Xmsg::printf("init fix adc\n");
            xcont->setParam(nblock, SLN_XFIXADC, (void*) (pack->getData() + 18));
        }

        if ((curStat == STAT_IDLE || curStat == STAT_POWEROFF) && reqStat == curStat) {
            xcont->stopScan(nblock);
        }

        if (xcont->isAlarm(nblock) && curStat == STAT_SCAN) {
            Xmsg::printf("OLIARM!!!\n");
            xcont->setParam(nblock, SLN_XREQSTAT, &(buf = STAT_ALARM));
            xcont->toNewStatus(nblock);
        }
        if (curStat == STAT_ALARM) {
            xcont->sendAlarmMessage(nblock);
        }
    }
}
